<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Registration extends MIS_Controller {

	function __construct()
	{
		parent::__construct();
		
		if(($this->is_loggedin && $this->router->fetch_method() == 'logout') or (!$this->is_loggedin && $this->router->fetch_method() != 'logout')){}
		else show_error('You have entered unauthorised place', 401, 'Error: 401 ( Unauthorized Access )');
	}
	
	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/buy_books
	 *	- or -  
	 * 		http://example.com/buy-books
	 *	- or -  
	 * 		http://example.com/buy_books/index
	 *	- or -  
	 * 		http://example.com/buy-books/index
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	public function index()
	{
		// Start Captcha Checking
		$this->loadRecaptcha();
		$this->form_validation->set_error_delimiters('<div class="form_error">', '</div>');
		$this->form_validation->set_rules('fullname', 'Name', 'trim|required|min_length[6]|max_length[50]');
		$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|callback_check_email');
		$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[6]|max_length[20]');
		$this->form_validation->set_rules('phone', 'Phone', 'trim|required|numeric');
		$this->form_validation->set_rules('iaccept', 'Terms', 'trim|required');

		if($this->form_validation->run()) 
		{
			$array['email'] = $this->input->post('email');
			$array['fullname'] = $this->input->post('fullname');
			$array['password'] = $this->input->post('password');
			$array['phone'] = $this->input->post('phone');
			if($this->config->item('registration_require_activation') == 1)
			{
				$array['random'] = $this->getRandomNumber();
				$array['is_active'] = 'notactive';
			}
			$userid = $this->m_user->insertUser($array);
			
			if($userid > 0)
			{
				$array['siteurl'] = site_url();
				$array['sitename'] = $this->config->item('site_name');
				
				if($this->config->item('registration_require_activation') == 1)
				{
					$array['subject'] = sprintf('%s activate your account to %s', $array['fullname'], $array['sitename']);
					$array['activation_url'] = site_url('registration/activate/' . $array['random']);
					$mailMesg = $this->parser->parse_string($this->get_config('registration_activation_template'), $array, TRUE);
					$this->sendHTMLMail($this->config->item('noreply_email'), $array['email'], $array['subject'], nl2br($mailMesg));
					$this->session->set_flashdata('success_mesg', 'You have successfully registered, please activate your account.');
				}
				else
				{
					$array['subject'] = sprintf('%s thanks for registering in %s', $array['fullname'], $array['sitename']);
					$array['loginurl'] = site_url('login');
					$mailMesg = $this->parser->parse_string($this->get_config('registration_complete_template'), $array, TRUE);
					$this->sendHTMLMail($this->config->item('noreply_email'), $array['email'], $array['subject'], nl2br($mailMesg));
					$this->session->set_flashdata('success_mesg', 'You have successfully registered, you can now login here.');
				}
				redirect('registration');
				return ;
			}
			else $this->session->set_flashdata('success_mesg', 'We can not register your data, please try again.');
		}
		$this->loadViewData['recaptcha_html'] = $this->recaptcha->get_html();
		// End Captcha Checking
		
		$this->loadViewData['banner_inc'] = false;
		$this->loadViewData['upper_footer_inc'] = false;
		$this->loadViewData['search_inc'] = false;
		$this->loadViewData['viewFile'] = 'v_registration';
		$this->load->view('layout', $this->loadViewData);
	}
	
	function is_unique_email()
	{
		$email = $this->input->post('email');
		if(filter_var($email, FILTER_VALIDATE_EMAIL) !== FALSE)
		{
			if($this->m_user->checkExistingEmail($email) === FALSE) print '<span style="color:green; font-size:10px;">Available</span>';
			else print '<span style="color:red; font-size:10px;">E-mail already exists</span>';
		}
		else print('<span style="color:red; font-size:10px;">Not valid email</span>');
	}
	
	function check_email($value)
	{
		if($this->m_user->checkExistingEmail($value) === FALSE) return TRUE;
		
		$this->form_validation->set_message('check_email', 'This email already exists.');
		return FALSE;
	}
	
	function activate()
	{
		$random = $this->uri->segment(3);
		if($random)
		{
			if($this->m_user->checkRandomNumberExists($random))
			{
				if(($userid = $this->m_user->activateRandomNumber($random)) !== FALSE)
				{
					$this->m_user->loginWithUserid($userid);
					$array = $this->session->userdata('userinfo');
					$array['subject'] = "Thankyou for activating your account";
					$array['loginurl'] = site_url('login');
					$array['siteurl'] = site_url();
					$array['sitename'] = $this->config->item('site_name');
					$mailMesg = $this->parser->parse_string($this->get_config('registration_activation_success_template'), $array, TRUE);
					$this->sendHTMLMail($this->config->item('noreply_email'), $array['email'], $array['subject'], nl2br($mailMesg));
					$this->session->set_flashdata('success_mesg', 'You have successfully activated your account.');
					$this->redirectAfterLogin();
					return ;
				}
				else $this->session->set_flashdata('error_mesg', 'Activation failed, please contact site administrator.');
			}
			else  $this->session->set_flashdata('error_mesg', 'Invalid Access. Check URL');
		}
		else $this->session->set_flashdata('error_mesg', 'Invalid Access');
		redirect('registration');
	}
	
	function login()
	{
		$this->load->library('form_validation');
		$this->form_validation->set_error_delimiters('<div class="form_error">', '</div>');
		$this->form_validation->set_rules('login_email', 'Email', 'trim|required|valid_email|callback_check_email_exists|callback_check_email_active');
		$this->form_validation->set_rules('login_password', 'Password', 'trim|required|min_length[6]|max_length[20]');
		
		if($this->form_validation->run())
		{
			$email = $this->input->post('login_email');
			$pass = $this->input->post('login_password');
			
			if(($userid = $this->m_user->getUserIdForCredential($email, $pass)) !== FALSE)
			{
				$this->m_user->loginWithUserid($userid);
				$this->session->set_flashdata('success_mesg', 'You have successfully loggedin in your account.');
				$this->redirectAfterLogin();
			}
			else $this->session->set_flashdata('error_mesg', 'Login credential mismatched.');
		}
		
		$this->loadRecaptcha();
		$this->loadViewData['recaptcha_html'] = $this->recaptcha->get_html();
		
		$this->loadViewData['banner_inc'] = false;
		$this->loadViewData['upper_footer_inc'] = false;
		$this->loadViewData['search_inc'] = false;
		$this->loadViewData['viewFile'] = 'v_registration';
		$this->load->view('layout', $this->loadViewData);
	}
	
	function check_email_exists($value)
	{
		if($this->m_user->checkExistingEmail($value) === TRUE) return TRUE;
		
		$this->form_validation->set_message('check_email_exists', 'This email not exists in our database.');
		return FALSE;
	}
	
	function check_email_active($value)
	{
		if($this->m_user->checkActiveEmail($value) === TRUE) return TRUE;
		
		$this->form_validation->set_message('check_email_active', 'Please activate your account.');
		return FALSE;
	}
	
	function logout()
	{
		$this->m_user->logoutUser();
		if($this->is_loggedin) $this->session->set_flashdata('success_mesg', 'You have successfully loggedout.');
		else $this->session->set_flashdata('error_mesg', 'You are not loogged in.');
		redirect('registration');
	}
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */